package org.abc.manager 
{
	import flash.display.Stage;
	import flash.events.Event;
	import flash.utils.getTimer;
	
	import org.abc.interfaces.ITick;
	import org.abc.interfaces.ITickManager;

	/**
	 * 
	 * 单例模式类
	 * @describe 	管理所有支持update的对象
	 * @author 		Mr.zheng
	 * @time 		2011-7-31 12:27
	 */
	public class EnterFrameTickManager implements ITickManager{
		private static var _instance:EnterFrameTickManager = null;
		public function EnterFrameTickManager(single:Single){
			
			if(single == null)
			{
				throw new Error("Can't create instance , Single is Null!");
			}
		}
		/**
		 * 单例引用
		 */
		public static function get instance():EnterFrameTickManager
		{
			if(_instance == null)
			{
				_instance = new EnterFrameTickManager(new Single());
			}
			return _instance;
		}
		
		//start-----------------------------------------------------------------------------
		/** update对象集合 */
		private var _tickVector:Vector.<ITick>;
		/** 场景 */
		private var _stage:Stage;
		
		/* public function */
		public function init(gameStage:Stage):void {
			_tickVector = new Vector.<ITick>();
			_stage = gameStage;
			_stage.addEventListener(Event.ENTER_FRAME, onEnterFrame);
		}
		public function addTick(tick:ITick):void {
			_tickVector.push(tick);
		}
		public function removeTick(tick:ITick):void {
			var index:int = _tickVector.indexOf(tick);
			if (index != -1) {
				_tickVector.splice(index, 1);
			}
		}
		/* private function */
		private function onEnterFrame(e:Event):void 
		{
			_tickVector.forEach(onTick);
		}
		private function onTick(item:ITick, index:int, vector:Vector.<ITick>):void {
			if(item.tickGap<=0)return;
			var unExecuteTime:int;
			var currTime:int = getTimer();
			unExecuteTime = int((currTime-item.startTime) / item.tickGap)-item.executeTime;
			while (unExecuteTime>0){
				item.tick();
				item.executeTime++;
				unExecuteTime--;
			}
			
		}
	}
}
class Single{}